package com.huichaoliu.stylist.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.huichaoliu.adapters.FragmentShoppingAdapter;
import com.huichaoliu.adapters.ProductAdapter;
import com.huichaoliu.app.R;
import com.huichaoliu.data.Config;
import com.huichaoliu.data.UtilInfo;
import com.huichaoliu.view.Mpop;
import com.huichaoliu.view.Mpop.PopClick;
import com.rederxu.request.HTTPRequest;
import com.rederxu.request.onRequestOverListener;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ShoppingIncludeFragment extends Fragment implements
		OnClickListener, PopClick {
	// tools
	Context context;

	// Views
	View v;
	LinearLayout r_cost;
	LinearLayout r_season;
	LinearLayout r_type;

	TextView t_cost;
	TextView t_season;
	TextView t_type;

	GridView gridView;
	TextView t_btn;

	// adapter
	FragmentShoppingAdapter adapter;

	// values
	List<UtilInfo> list;
	int typePart = 0;
	String typeSeason = "";
	String typeStyle = "";
	String typeMax = "";
	String typeMin = "";

	List<UtilInfo> style;

	// pop
	Mpop pop_cost;
	Mpop pop_season;
	Mpop pop_type;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (v == null) {
			v = inflater.inflate(R.layout.shopping_include_fragment, container,
					false);
		}
		ViewGroup parent = (ViewGroup) v.getParent();
		if (parent != null) {
			parent.removeView(v);
		}
		context = getActivity();
		initView();
		getData();
		v.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dissmissAll();
			}
		});
		return v;
	}
	
	public void setTypePart(int typePart){
		this.typePart = typePart;
	}

	private void initView() {
		r_cost = (LinearLayout) v.findViewById(R.id.shopping_filter_cost);
		r_season = (LinearLayout) v.findViewById(R.id.shopping_filter_season);
		r_type = (LinearLayout) v.findViewById(R.id.shopping_filter_type);

		t_cost = (TextView) v.findViewById(R.id.shopping_filter_cost_txt);
		t_season = (TextView) v.findViewById(R.id.shopping_filter_season_txt);
		t_type = (TextView) v.findViewById(R.id.shopping_filter_type_txt);

		gridView = (GridView) v.findViewById(R.id.shopping_grid);
		t_btn = (TextView) v.findViewById(R.id.shopping_click_btn);

		r_cost.setOnClickListener(this);
		r_season.setOnClickListener(this);
		t_btn.setOnClickListener(this);

		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				dissmissAll();
				list.get(arg2).setCheck(!list.get(arg2).isCheck());
				adapter.notifyDataSetChanged();
			}
		});
	}

	private void getData() {
		list = new ArrayList<UtilInfo>();
		// for (int i = 0; i < 11; i++) {
		// list.add(new UtilInfo());
		// }
		Bundle bundle = new Bundle();
		bundle.putString("userId", "51b634b6361a07f1");
		bundle.putString("type", typePart + "");
		Log.i("Hello", "get res ");
		HTTPRequest.POST(getActivity(), Config.REQUEST_URLS.URL_COMMODITY_LIST,
				bundle, new onRequestOverListener() {

					@Override
					public void onRequestOver(String result) {
						try {
							JSONObject jo = new JSONObject(result);
							if (jo.getInt("code") != 0) {
								Toast.makeText(getActivity(),
										jo.getString("message"), 1).show();
								return;
							}
							Message msg = new Message();
							msg.what = 1;
							msg.obj = result;
							mHandler.sendMessage(msg);

						} catch (JSONException e) {
							if (result.contains("500")) {
								try {
									JSONObject jo = new JSONObject(result);
									Toast.makeText(getActivity(),
											jo.getString("message"), 1).show();
								} catch (JSONException e2) {

								}
							}
							e.printStackTrace();
						}
					}
				});

		HTTPRequest.POST(getActivity(),
				Config.REQUEST_URLS.URL_COMMODITY_STYLE_LIST, bundle,
				new onRequestOverListener() {
					@Override
					public void onRequestOver(String result) {
						try {
							JSONObject jo = new JSONObject(result);
							if (jo.getInt("code") != 0) {
								Toast.makeText(getActivity(),
										jo.getString("message"),
										Toast.LENGTH_SHORT).show();
								return;
							}
							Message msg = new Message();
							msg.what = 2;
							msg.obj = result;
							mHandler.sendMessage(msg);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});

	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.shopping_filter_cost:
			if (pop_cost == null) {
				pop_cost = new Mpop(context, r_cost.getWidth(), this);
			}
			if (pop_season != null) {
				pop_season.dismiss();
			}

			if (pop_type != null) {
				pop_type.dismiss();
			}
			if (pop_cost.isShowing()) {
				pop_cost.dismiss();
			} else {
				pop_cost.showPop(Mpop.COST, t_cost);
			}
			break;
		case R.id.shopping_filter_season:
			if (pop_season == null) {
				pop_season = new Mpop(context, r_season.getWidth(), this);
			}
			if (pop_cost != null) {
				pop_cost.dismiss();
			}

			if (pop_type != null) {
				pop_type.dismiss();
			}
			if (pop_season.isShowing()) {
				pop_season.dismiss();
			} else {
				pop_season.showPop(Mpop.SEASON, t_season);
			}

			break;
		case R.id.shopping_filter_type:
			if (pop_type == null) {
				pop_type = new Mpop(context, r_type.getWidth(), this);
			}
			if (pop_cost != null) {
				pop_cost.dismiss();
			}

			if (pop_season != null) {
				pop_season.dismiss();
			}
			if (pop_type.isShowing()) {
				pop_type.dismiss();
			} else {
				pop_type.showPop(Mpop.TYPE, r_type, style);
			}
			break;
		case R.id.shopping_click_btn:

			break;

		default:
			break;
		}
	}

	public void dissmissAll() {
		if (pop_cost != null) {
			pop_cost.dismiss();
		}

		if (pop_season != null) {
			pop_season.dismiss();
		}

		if (pop_type != null) {
			pop_type.dismiss();
		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (hidden) {
			dissmissAll();
		}
	}

	public void setText(String str) {
		if (t_btn != null) {
			t_btn.setText(str);
		}
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Log.i("Hello", "1");
				parseData((String) msg.obj, list);
				adapter = new FragmentShoppingAdapter(list, context);
				gridView.setAdapter(adapter);
				break;
			case 2:
				parseStyle((String) msg.obj);
				r_type.setOnClickListener(ShoppingIncludeFragment.this);
				break;

			default:
				break;
			}
		}
	};

	private void parseData(String result, List<UtilInfo> list) {
		try {
			JSONObject obj = new JSONObject(result);
			JSONArray arry = obj.getJSONArray("response");
			list = new ArrayList<UtilInfo>();
			for (int i = 0; i < arry.length(); i++) {
				UtilInfo info = new UtilInfo();
				info.setPicPath(arry.getJSONObject(i).getString("image"));
				list.add(info);
			}
			Log.i("Hello", "size = " + list.size());

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void parseStyle(String result) {
		try {
			JSONObject obj = new JSONObject(result);
			JSONArray arry = obj.getJSONArray("response");
			style = new ArrayList<UtilInfo>();
			for (int i = 0; i < arry.length(); i++) {
				UtilInfo info = new UtilInfo();
				info.setPicPath(arry.getJSONObject(i).getString("styleId"));
				info.setUserId(arry.getJSONObject(i).getString("name"));
				style.add(info);
			}
			Log.i("Hello", "size = " + style.size());

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void clickCost(String min, String max, String text) {
		typeMin = min;
		typeMax = max;
		t_cost.setText(text);
		pop_cost.dismiss();
		changeData();
		Log.i("Hello", "min = " + min + " ; max = " + max + " ; text = " + text);
	}

	@Override
	public void clickSeason(String code, String text) {
		typeSeason = code;
		t_season.setText(text);
		pop_season.dismiss();
		changeData();
		Log.i("Hello", "code = " + code + " ; text = " + text);
	}

	@Override
	public void clickStyle(String id, String text) {
		typeStyle = id;
		t_type.setText(text);
		pop_type.dismiss();
		changeData();
		Log.i("Hello", "id = " + id + " ; text = " + text);
	}

	private void changeData() {
		Bundle bundle = new Bundle();
		bundle.putString("userId", "51b634b6361a07f1");
		if (!typeMax.equals("")) {
			bundle.putString("maxp", typeMax);
		}
		if (!typeMin.equals("")) {
			bundle.putString("minp", typeMin);
		}
		if (!typeStyle.equals("")) {
			bundle.putString("style", typeStyle);
		}
		if (!typeSeason.equals("")) {
			bundle.putString("season", typeSeason);
		}
		bundle.putString("type", typePart + "");
		HTTPRequest.POST(getActivity(), Config.REQUEST_URLS.URL_COMMODITY_LIST,
				bundle, new onRequestOverListener() {

					@Override
					public void onRequestOver(String result) {
						Log.i("Hello", "bundle = " + result);
						try {
							JSONObject jo = new JSONObject(result);
							if (jo.getInt("code") != 0) {
								Toast.makeText(getActivity(),
										jo.getString("message"), 1).show();
								return;
							}
							Message msg = new Message();
							msg.what = 1;
							msg.obj = result;
							mHandler.sendMessage(msg);

						} catch (JSONException e) {
							if (result.contains("500")) {
								try {
									JSONObject jo = new JSONObject(result);
									Toast.makeText(getActivity(),
											jo.getString("message"), 1).show();
								} catch (JSONException e2) {

								}
							}
							e.printStackTrace();
						}
					}
				});
	}

}
